# -*- coding:utf-8 -*-
import cv2
import numpy as np
import sys
import json

# ---------------------------------

# test script
# python cstamp.py d:\a.png d:\b.png


def clearStamp(tarpath, dispath):

    try:
        targetImg = cv2.imdecode(np.fromfile(
            tarpath, dtype=np.uint8), cv2.IMREAD_COLOR)

        # 获取图片高度，宽度，色彩通道数量
        orgh, orgw, channel = targetImg.shape

        # 使用cv.resize对图像进行缩放
        resized_img = cv2.resize(targetImg, (orgw//2, orgh//2))

        # 输出缩小后的图像
        newfilename = dispath.replace("pre_", "")

        last_dot_index = newfilename.rfind('.')       
        if last_dot_index != -1:        
            newfilename = newfilename[:last_dot_index] + '_S' + newfilename[last_dot_index:]         
                    
        cv2.imencode('.png', resized_img)[1].tofile(newfilename)

        # 分离图片的通道
        blue_c, green_c, red_c = cv2.split(targetImg)

        # 利用大津法自动选择阈值
        thresh, ret = cv2.threshold(red_c, 0, 255, cv2.THRESH_OTSU)

        # 对阈值进行调整
        filter_condition = int(thresh*1.2)

        # 移除红色的印章
        _, red_thresh = cv2.threshold(
            red_c, filter_condition, 255, cv2.THRESH_BINARY)

        # 把图片转回3通道
        result_img = np.expand_dims(red_thresh, axis=2)
        result_img = np.concatenate(
            (result_img, result_img, result_img), axis=-1)

        cv2.imencode('.png', result_img)[1].tofile(dispath)

        return {"success": True, "errinfo": ""}

    except BaseException as e:
        return {"success": False, "errinfo": e}


def msgToNode(err, errtext):
    res = {
        'err': err,
        'errtext': errtext
    }

    # print 到 cmd 控制台
    # node 通过监听输出 回调判断处理状态
    print(json.dumps(res))


if "__main__" == __name__:
    if sys.argv.__len__() < 3:
        msgToNode(-1, "参数数量不足")
    else:
        res = clearStamp(sys.argv[1], sys.argv[2])
        if not res["success"]:
            msgToNode(-2, str(res["errinfo"]))
        else:
            msgToNode(100, "处理成功")
